package com.baizhi.sync3;

/**
 * 死锁
 * 当两个线程在持有各自锁对象的同时都在等待对方释放锁资源就会出现一种“僵持”状态，这个线程称之为死锁
 */
public class SyncDemo03 {
    private static Object chopsticks = new Object(); //筷子
    private static Object spoon = new Object(); //勺子

    public static void main(String[] args) {
       Thread np = new Thread(()->{
           try{
               System.out.println("北方人开始吃饭");
               System.out.println("北方人拿起了筷子.....");
               synchronized (chopsticks){
                   System.out.println("北方人使用筷子开始吃饭.....");
                   Thread.sleep(5000);
                   System.out.println("北方人吃完了饭，去拿勺子");
                   synchronized (spoon){
                       System.out.println("北方人拿起了勺子，准备喝汤");
                       Thread.sleep(5000);
                   }
                   System.out.println("北方人放下了勺子");
               }
               System.out.println("北方人放下了筷子，吃饭完毕");

           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       });



       Thread sp = new Thread(()->{
           try{
               System.out.println("南方人开始吃饭");
               System.out.println("南方人去拿勺子...");
               synchronized (spoon){
                   System.out.println("南方人拿起勺子准备喝汤");
                   Thread.sleep(5000);
                   System.out.println("南方人喝汤完毕，去拿筷子");
                   synchronized (chopsticks){
                       System.out.println("南方人拿起了筷子开始吃饭");
                       Thread.sleep(5000);
                   }
                   System.out.println("南方人放下了筷子");
               }
               System.out.println("南方人放下了勺子，吃饭完毕");

           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       });


       np.start();
       sp.start();
    }
}
